#include "stm32f10x.h"                  // Device header
#include "OLED.h"
#include "Delay.h"
#include "led.h"
#include <string.h>
#include "DX_WF24.h"


int main(void)
{
	Led_Init();
	OLED_Init();
	
	int8_t tcpStatus = 0;
	
	// Wifi模块初始化
	int8_t initState = Wifi_Init();
	if (initState == 1) {
		OLED_ShowString(1, 1, "Wifi ok");
		tcpStatus = 1;

		// 建立tcp连接
		int8_t connState = Wifi_ConnectTcp("10.10.1.20", 8888);
		if (connState == 1) {
			OLED_ShowString(2, 1, "Conn ok");
			tcpStatus = 2;
			
			// 发送数据
			Tcp_SendData("Hello, world!\r\n");
			
			// 断开连接
//			int8_t closeState = Wifi_CloseTcp();
//			if (closeState) {
//				OLED_ShowString(3, 1, "Close ok");
//			} else {
//				OLED_ShowString(3, 1, "Conn error:");
//				OLED_ShowSignedNum(3, 13, closeState, 1);
//			}
		} else {
			OLED_ShowString(2, 1, "Conn error:");
			OLED_ShowSignedNum(2, 12, connState, 1);
		}
	} else {
		OLED_ShowString(1, 1, "Wifi error:");
		OLED_ShowSignedNum(1, 12, initState, 1);
	}
	
	uint16_t count = 0;
	OLED_ShowNum(4, 1, count, 10);
	
	if (tcpStatus == 2) {
		char rxData[96];
		while(1) {
			while (Tcp_hasNextData()) {
				Tcp_readNextData(rxData);
				OLED_ShowString(3, 1, "                ");
				OLED_ShowString(3, 1, rxData);
				if (strcmp(rxData, "on") == 0) {
					Led_On();
					Tcp_SendData("OK\r\n");
				} else if (strcmp(rxData, "off") == 0) {
					Led_Off();
					Tcp_SendData("OK\r\n");
				} else if (strcmp(rxData, "turn") == 0) {
					Led_Turn();
					Tcp_SendData("OK\r\n");
				} else {
					Tcp_SendData("UNKNOW\r\n");
				}
			}
			count ++;
			OLED_ShowNum(4, 1, count, 10);
		}
	}
}
